/*
 * @Author: 晴鸢. 3013433857@qq.com
 * @Date: 2025-10-19 14:22:55
 * @LastEditors: 晴鸢. 3013433857@qq.com
 * @LastEditTime: 2025-10-29 14:30:06
 * @FilePath: /Learn/tcp/Task.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include <iostream>
#include <string>
#include "Log.hpp"
class Task
{
public:
    Task(int sockfd, const std::string &ip, uint16_t &port)
        : _sockfd(sockfd), _clientip(ip), _clientport(port)
    {
    }
    Task()
    {
    }
    void run()
    {
        char message[4096];
        while (1)
        {
            ssize_t n = read(_sockfd, message, sizeof(message));
            if (n > 0)
            {
                message[n] = 0;
                std::cout << "client say:#" << message << std::endl;
                std::string str = "server echo#";
                str += message;
                n = write(_sockfd, str.c_str(), str.size());
                if (n < 0)
                {
                    lg(Warning, "write errno,errno:%d,errstring:%s", errno, strerror(errno));
                }
            }
            else if (n == 0)
            {
                lg(Info, "%s:%d quit,server close sockfd:%d", _clientip.c_str(), _clientport, _sockfd);
                break;
            }
            else
            {
                lg(Warning, "read error,sockfd:%d,clientport:%d,clientip:%s", _sockfd, _clientport, _clientip);
                break;
            }
        }
        close(_sockfd);
    }
    void operator()()
    {
        run();
    }

    ~Task()
    {
    }

private:
    int _sockfd;
    std::string _clientip;
    uint16_t _clientport;
};
